package com.projectx.action;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Looper;
import android.text.InputType;
import android.text.Layout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.google.android.material.textfield.TextInputLayout;
import com.google.gson.Gson;
import com.projectx.R;
import com.projectx.action.talk.TalkListActivity;
import com.projectx.entity.User;
import com.projectx.entity.UserData;
import com.projectx.util.ActivityManage;
import com.projectx.util.MyAlertDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

public class SettingActivity extends AppCompatActivity {
    private String accountName;
    private String newPassword = TalkListActivity.password;
    private TextView setPassword;
    private TextView setRealName;
    private TextView setId;
    private TextView setSex;
    private TextView setMail;
    private TextView setPhone;
    private TextView setQQ;
    private Button setCommit;
    private TextInputLayout textInputLayout;
    private EditText editText;
    private User userData = new User();
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        final Intent intent = getIntent();
        accountName = intent.getStringExtra("accountName");
        setPassword = findViewById(R.id.setting_password);
        setRealName = findViewById(R.id.setting_real_name);
        setId = findViewById(R.id.setting_id);
        setSex = findViewById(R.id.setting_sex);
        setMail = findViewById(R.id.setting_mail);
        setPhone = findViewById(R.id.setting_phone);
        setQQ = findViewById(R.id.setting_qq);
        setCommit = findViewById(R.id.setting_commit);

        final MyAlertDialog myAlertDialog = new MyAlertDialog();

        try {
            getSupportActionBar().hide(); //去除标题栏
        } catch (NullPointerException e){
            Log.d("KMH","没有状态栏标题");
        }

        FutureTask<User> task = userInfoTask;
        new Thread(task).start();

        setPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final View layout = LayoutInflater.from(SettingActivity.this).inflate(R.layout.item_text_input,null);
                final View view = layout.findViewById(R.id.commonTextInput);
                editText = layout.findViewById(R.id.commonEditText);
                textInputLayout = layout.findViewById(R.id.commonEditField);
                textInputLayout.setEndIconMode(TextInputLayout.END_ICON_PASSWORD_TOGGLE);
                editText.setInputType(0x00000081);//这是密码的type
                textInputLayout.setHint("请输入新密码");
                showPasswordDialog(view,"更改密码",setPassword);

            }
        });

        setRealName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final View layout = LayoutInflater.from(SettingActivity.this).inflate(R.layout.item_text_input,null);
                final View view = layout.findViewById(R.id.commonTextInput);
                textInputLayout = layout.findViewById(R.id.commonEditField);
                editText = layout.findViewById(R.id.commonEditText);
                myAlertDialog.editTextDialog(SettingActivity.this,view,textInputLayout,setRealName,"真实姓名","输入您的真实姓名");
            }
        });

        setId.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final View layout = LayoutInflater.from(SettingActivity.this).inflate(R.layout.item_text_input,null);
                final View view = layout.findViewById(R.id.commonTextInput);
                textInputLayout = layout.findViewById(R.id.commonEditField);
                editText = layout.findViewById(R.id.commonEditText);
                editText.setInputType(InputType.TYPE_CLASS_NUMBER);
                myAlertDialog.editTextDialog(SettingActivity.this,view,textInputLayout,setId,"学号","输入您的学号");
            }
        });

        setSex.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String [] choices = {"帅哥","美女","秘密"};
                int init = -1;
                switch (setSex.getText().toString()){
                    case "美女":
                        init = 0;
                        break;
                    case "帅哥":
                        init = 1;
                        break;
                    case "秘密":
                        init = 2;
                        break;
                }
                myAlertDialog.singleChoiceDialog(SettingActivity.this,"请选择性别",choices,setSex,init);
            }
        });

        setMail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final View layout = LayoutInflater.from(SettingActivity.this).inflate(R.layout.item_text_input,null);
                final View view = layout.findViewById(R.id.commonTextInput);
                textInputLayout = layout.findViewById(R.id.commonEditField);
                editText = layout.findViewById(R.id.commonEditText);
                myAlertDialog.editTextDialog(SettingActivity.this,view,textInputLayout,setMail,"设置邮箱","输入您的邮箱");
            }
        });

        setPhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final View layout = LayoutInflater.from(SettingActivity.this).inflate(R.layout.item_text_input,null);
                final View view = layout.findViewById(R.id.commonTextInput);
                textInputLayout = layout.findViewById(R.id.commonEditField);
                editText = layout.findViewById(R.id.commonEditText);
                editText.setInputType(InputType.TYPE_CLASS_NUMBER);
                myAlertDialog.editTextDialog(SettingActivity.this,view,textInputLayout,setPhone,"手机号码","输入您的手机号码");
            }
        });

        setQQ.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final View layout = LayoutInflater.from(SettingActivity.this).inflate(R.layout.item_text_input,null);
                final View view = layout.findViewById(R.id.commonTextInput);
                textInputLayout = layout.findViewById(R.id.commonEditField);
                editText = layout.findViewById(R.id.commonEditText);
                editText.setInputType(InputType.TYPE_CLASS_NUMBER);
                myAlertDialog.editTextDialog(SettingActivity.this,view,textInputLayout,setQQ,"QQ号","输入您的QQ号码");
            }
        });

        setCommit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (newPassword != null && newPassword.length() > 0){
                    userData.setPassword(newPassword);
                }
                userData.setUserName(accountName);
                userData.setFlag(5);
                userData.setMail(setMail.getText().toString());
                userData.setRealName(setRealName.getText().toString());
                if (setSex.getText().toString().equals("保密")){
                    userData.setSex(2);
                } else {
                    userData.setSex(setSex.getText().toString().equals("帅哥") ? 1 : 0);
                }
                try {
                    userData.setId(Long.parseLong(setId.getText().toString()));
                } catch (Exception e){
                    Toast.makeText(SettingActivity.this, "学号格式不正确", Toast.LENGTH_SHORT).show();
                    return;
                }
                try {
                    userData.setPhone(Long.parseLong(setPhone.getText().toString()));
                } catch (Exception e){
                    Toast.makeText(SettingActivity.this, "手机号格式不正确", Toast.LENGTH_SHORT).show();
                    return;
                }
                try {
                    userData.setQq(Long.parseLong(setQQ.getText().toString()));
                } catch (Exception e){
                    Toast.makeText(SettingActivity.this, "QQ格式不正确", Toast.LENGTH_SHORT).show();
                    return;
                }
                //没有错误提交数据
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Socket socket = new Socket("106.15.192.117", 2333);
                            DataInputStream dis = new DataInputStream(socket.getInputStream());
                            DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
                            dos.writeUTF(new Gson().toJson(userData));
                            dos.flush();
                            String result = dis.readUTF();
                            try {
                                final JSONObject getMessage = new JSONObject(result);
                                Log.d("kmh", "Setting run: " + getMessage);
                                if (getMessage.getInt("code") == 0){
                                    Looper.prepare();
                                    Toast.makeText(SettingActivity.this,"保存成功",Toast.LENGTH_SHORT).show();
                                    Looper.loop();
                                } else {
                                    Looper.prepare();
                                    //出了任何异常都判定为上传失败
                                    Toast.makeText(SettingActivity.this, "保存失败", Toast.LENGTH_SHORT).show();
                                    Looper.loop();
                                }//显示上传失败
                            } catch (JSONException e) {
                                Log.d("kmh", "doInBackground: 后端JSON字符串有问题祭天吧");
                            } finally {
                                Looper.prepare();
                                Toast.makeText(SettingActivity.this, "保存失败", Toast.LENGTH_SHORT).show();
                                Looper.loop();
                                dis.close();
                                dos.close();
                                socket.close();
                            }
                        } catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                }).start();
                finish();
            }
        });
    }

    private void showPasswordDialog(View view, String title, final TextView content){
        AlertDialog.Builder alert = new AlertDialog.Builder(this);
        alert.setTitle(title).setView(view);
        alert.setNegativeButton("取消",null);
        alert.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (editText.getText().length() == 0){
                    textInputLayout.setError("密码不能为空");
                    return;
                }
                newPassword = editText.getText().toString();
                StringBuilder str = new StringBuilder();
                for (int ii = 0;ii < newPassword.length();ii++)
                {
                    str.append("*");
                }
                content.setText(str.toString());
            }
        });
        alert.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                dialog.dismiss();
            }
        });
        alert.show();
    }

    /**
     * 获取个人信息
     */
    private FutureTask<User> userInfoTask = new FutureTask<>(new Callable<User>() {
        @Override
        public User call() {
            try {
                Socket socket = new Socket("106.15.192.117", 2333);
                Gson gson = new Gson();
                User user = new User();
                user.setFlag(4);
                user.setUserName(TalkListActivity.username);
                user.setPassword(TalkListActivity.password);
                String message = gson.toJson(user);
                DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
                dataOutputStream.writeUTF(message);
                dataOutputStream.flush();
                DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
                String netStr = dataInputStream.readUTF();
                try {
                    JSONObject getMessage = new JSONObject(netStr);
                    if (getMessage.getInt("code") == -1){
                        throw new Exception("服务器错误");
                    } else if (getMessage.getInt("code") == 0){
                        userData = gson.fromJson(getMessage.getString("data"),User.class);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                setPassword.setText("***");
                                setId.setText(String.format("%s",userData.getId()));
                                setPhone.setText(String.format("%s",userData.getPhone()));
                                setQQ.setText(String.format("%s",userData.getQq()));
                                setMail.setText(userData.getMail());
                                setRealName.setText(userData.getRealName());
                                if (userData.getSex() < 2){
                                    setSex.setText(userData.getSex() == 0 ? "美女" : "帅哥");
                                } else {
                                    setSex.setText("保密");
                                }

                            }
                        });
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    Log.d("kmh", "doInBackground: 后端JSON字符串有问题祭天吧");
                }

            } catch (Exception ioe) {
                Looper.prepare();
                Toast.makeText(SettingActivity.this, "服务器错误", Toast.LENGTH_SHORT).show();
                Looper.loop();
                ioe.printStackTrace();
            }
            return userData;
        }
    });
}
